<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\guess\controller;

use app\admin\model\BatMatchModel;
use app\admin\model\BatOrderModel;
use app\admin\model\ChangeCoinModel;
use app\admin\model\GiveModel;
use app\admin\model\MemberModel;
use app\admin\model\SizeModel;
use app\admin\model\VictoryModel;
use cmf\controller\RestBaseController;
use api\index\controller\CommonController;
use think\Request;
use think\Db;

class GuessController extends RestBaseController
{
    protected $noNeedLogin = [];


    /**
     * @param Request $request
     * @throws \think\exception\DbException
     * 竞猜列表
     */
    public function index(Request $request)
    {
        if (!$request->isPost()) {
            $this->success('请求方式错误');
        }
        $this->checkValidate($request->post(), config('check.home'));
        if ($request->type == 3){//我购买的
            $batMatch = BatOrderModel::field('id,bet_coin,bat_id,win_coin,create_time,status')
                ->where('member_id',$this->getUserId())
                ->with(['batMatch'=>function($query){
                    $query->field('id,lea_name,status,team_main_id,team_pass_id,main_score,pass_score,match_time');
                    $query->with(['teamMainName','teamPassName']);
                }])
                ->withAttr('bat_match.match_time',function ($vault){
                    return  date('m-d',$vault);
                })
                ->order('create_time desc')
                ->paginate(config('verify.limit'));
            $this->success('成功', $batMatch);
        }
        $batMatch = BatMatchModel::field('id,lea_name,team_main_id,team_pass_id,match_time')
            ->where('type', $request->type)
            ->where('status', '<', BatMatchModel::EVEMT_STATUS_BARREN)//状态不是已出结果的
            ->with(['teamMainName','teamPassName','give','size','victory','member'])
            ->order('match_time desc')
            ->paginate(config('verify.limit'))->each(function ($item){
                $item->buy_num = count($item->member);
                unset($item->member);
            });
        $this->success('成功', $batMatch);

    }

    /**
     * @param Request $request
     * 投注
     */
    public function bet(Request $request)
    {
        if (!$this->request->isPost()) {
            $this->success('请求方式错误');
        }
        $param = $request->post();
        $this->checkValidate($param, config('check.bet'));
        if (!$bat = BatMatchModel::get($param['bat_id'])) {
            $this->error('对战数据不存在');
        }
        if ($bat->status >= BatMatchModel::EVEMT_STATUS_BARREN) {
            $this->error('投注已经结束');
        }
        if ($bat->status == BatMatchModel::EVEMT_STATUS_PENDING) {
            //修改对战状态
            $bat->status = BatMatchModel::EVEMT_STATUS_START;
            $bat->save();
        }

        $guess_type = $param['guess_type'];
        switch ($param['type']) { //根据类型返回赔率
            case 0:  //猜胜负
                $field = VictoryModel::$matchResult[$guess_type];
                $guess = $bat->victory;
                break;
            case 1:  //猜让球
                $field = GiveModel::$matchResult[$guess_type];
                $guess = $bat->give;
                break;
            case 2:  //猜大小
                $field = SizeModel::$matchResult[$guess_type];
                $guess = $bat->size;
                break;
            default:
                $this->error('类型错误');
                break;
        }
        $member = MemberModel::get($this->userId);

        Db::transaction(function () use ($param, $member, $guess, $guess_type ,$field,$bat) {

            $bet = BatOrderModel::create([
                'bat_id'     => $param['bat_id'],
                'member_id'  => $member->id,
                'type'       => $param['type'],
                'guess_id'   => $guess->id,
                'guess_type' => $guess_type,
                'bet_coin'   => $param['bet_num'],
                'bet_num'    => $param['bet_num'],
                'odd'        => $guess->$field, //赔率
                'win_coin'   => bcmul($param['bet_num'], $guess->$field,2),
            ]);

            //添加球币变动
            CommonController::changeCoin($this->getUserId(), ChangeCoinModel::BET, $bet->id, '投注消费', -$param['bet_num'], bcsub($member->coin, $param['bet_num']));
            //修改用户球币
            $member->setDec('coin', $param['bet_num']);
            //增加竞猜次数
            $member->setInc('guess_num');
            //增加投注人数
            $bat->setInc('real_num');
        });
        $this->success('成功');
    }


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 投注规则
     */
    public function guessRule()
    {
        if (!$this->request->isGet()) {
            $this->error('请求方式错误');
        }
        if (!$info = Db::name('info_set')->find()) {
            $this->error('数据不存在');
        }
        $this->success('成功', $info['guess_rule']);
    }


}
